<?php

Class Messages {
    
    
    #var $table = "messages";
    
    static function sendUnicMessage ($user, $text, $from = false){
        $sql = "SELECT * FROM `".PREFIX_TABLE."messages` WHERE  `user` = '".$user."' ORDER BY `time` DESC LIMIT 1  ";
        if(!$result = DBConnect::query($sql)){
            Connect::_error(mysql_error());
            return false;
        }
        $result = DBConnect::getOne($result);
        
        if($result['text'] == $text) return true;
        
        $sql = "INSERT INTO `".PREFIX_TABLE."messages` (`user`, `from`, `text`, `time`) 
                VALUES ('".$user."', '".$from."', '".$text."', '".time()."') ";        
        if(!$result = DBConnect::query($sql)){
            Connect::_error(mysql_error());
            return false;
        }
        return true;
    }
    
    
    static function send ($user, $text, $from = false){
        $sql = "INSERT INTO `".PREFIX_TABLE."messages` (`user`, `from`, `text`, `time`) 
                VALUES ('".$user."', '".$from."', '".$text."', '".time()."') ";        
        if(!$result = DBConnect::query($sql)){
            Connect::_error(mysql_error());
            return false;
        }
        return true;
    }
    
    static function del($user, $id){
        $sql = "DELETE FROM `".PREFIX_TABLE."messages` WHERE `user` = '".$user."' AND `id` = '".$id."' ";
        if(!$result = DBConnect::query($sql)){
            Connect::_error(mysql_error());
            return false;
        }
        return true;
    }
    
    static function getOld($user){
        return Messages::getAll($user, true, 1);
    }
    
    static function getAll($user, $old = false, $limit = false){
        $sql = "SELECT * FROM `".PREFIX_TABLE."messages` 
                WHERE `user` = '".$user."' ";
        
        if($old != false){
            $sql .= " ORDER BY `time` DESC ";
        }
        if($limit != false){
            $sql .= " LIMIT ".$limit;
        }
        if(!$result = DBConnect::query($sql)){
            Connect::_error(mysql_error());
            return false;
        }
        $_arr = array();
        while($arr = DBConnect::getOne($result)){
            $_arr[] = $arr;    
        }
                
        return $_arr; 
    }
}
?>